﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;

public partial class admin_BannerDetail : SitePage
{
    #region Fields
    public string Command
    {
        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }
        set { ViewState["Command"] = value; }

    }
    public string ThumImage
    {
        get
        {
            object o = ViewState["ThumImage"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ThumImage"] = value; }

    }
    public int Id
    {
        get
        {
            object o = ViewState["Id"];
            if (o != null) return (int)o;
            return int.MinValue;
        }
        set { ViewState["Id"] = value; }

    }
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            LoadData();
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();        
    }
    
    
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

    }
    #endregion

    #region Methods
    private void LoadData()
    {
        if (this.Command == "edit")
        {
            busBanner objBus = new busBanner();
            Banner objBanner = objBus.GetByID(this.Id);
            if (objBanner != null)
            {
               // txtTitle.Text = objBanner.Title.Trim();
                if (objBanner.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
                this.ThumImage = objBanner.FilePath;
                txtLink.Text = objBanner.Url;
                txtName.Text = objBanner.BannerName;
                F_StartDate.Text = clsConvert.String(objBanner.StartingDate);
                F_EndDate.Text = clsConvert.String(objBanner.EndingDate);
                BindImage(trImage, imgImage, lbtnDeleteImage, objBanner.FilePath);
            }
        }
    }
    private void InitData()
    {
      //  string validateGroup = "BannerDetail";
    //    vsumForm.ValidationGroup = btnSave.ValidationGroup =  cusImage.ValidationGroup =reqendDate.ValidationGroup=reqStartDate.ValidationGroup= validateGroup;
        //Init message
      //  reqStartDate.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Starting Date");
      //  reqendDate.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Ending Date");
       // cusImage.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Image");
        this.Command = clsQueryString.GetString("act");
        this.Id = clsQueryString.GetInt("id");
    }

    private void UpdateBanner(Banner objData)
    {
        busBanner objBus = new busBanner();
        objData.Id = this.Id;
        if (objBus.Update(objData))
            Response.Redirect("BannerList.aspx?" + this.GetPageQuery);
        else lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
    }

    private void InsertBanner(Banner objBanner)
    {
        busBanner objBus = new busBanner();
        if (objBus.Insert(objBanner))
            Response.Redirect("BannerList.aspx?" + this.GetPageQuery);
        else
        {
            this.DeleteImage(objBanner.FilePath);
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ValidateForm())
        {
            //get datavalue
            Banner objData = new Banner();
            objData.CreatedBy =objData.UpdatedBy=this.userloginName;
            objData.CreatedDate =objData.UpdatedDate=clsDateTime.Now;           
            objData.Url = txtLink.Text.Trim();
            objData.BannerName = txtName.Text;
            objData.StartingDate = clsConvert.Date(F_StartDate.Text.Trim());
            objData.EndingDate = clsConvert.Date(F_EndDate.Text.Trim());
            objData.FilePath = UploadThumImage(fulImage, this.ThumImage);
            if (chkIsActive.Checked)
                objData.IsActive = true;
            else
                objData.IsActive = false;             
            if (this.Command == "edit")
                UpdateBanner(objData);
            else
                InsertBanner(objData);
        }        
    }

    private string UploadThumImage(FileUpload _ful, string _oldImage)
    {


        string result = _oldImage;
        if (_ful.HasFile)
        {
            string fileNameUpload = _ful.FileName;
            string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
            string fileName = Guid.NewGuid().ToString();
            result = fileName + extFile;
            string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_BANNER_FOLDER);
            if (!string.IsNullOrEmpty(_oldImage))
            {
                this.DeleteImage(_oldImage);
            }
            fullPath += fileName + extFile;
            _ful.SaveAs(fullPath);
            //
            ////Redrawimage
            //System.Drawing.Imaging.ImageFormat imgFormat = clsImage.GetImageFormat(extFile);
            //string pathThumb = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_BANNER_THUMB_FOLDER);
            //pathThumb += fileName + extFile;
            //using (System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(fullPath))
            //{
            //    System.Drawing.Image imgPhotoSub = clsImage.ScaleCrop(imgPhoto, 120, 120, AnchorPosition.Center, true, false);
            //    imgPhotoSub.Save(pathThumb, imgFormat);
            //    imgPhotoSub.Dispose();
            //}           
        }
        return result;
    }
    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_BANNER_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        //path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_BANNER_THUMB_FOLDER);
        //clsFile.DeleteFile(path + _orgImageFileName);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
      
        Response.Redirect("BannerList.aspx?" + this.GetPageQuery);
    }
    protected void lbtnDeleteImage_Click(object sender, EventArgs e)
    {
        //Step 1: Delete Image InDB
        busBanner objBus = new busBanner();
        Banner objTip = objBus.GetByID(this.Id);
        if (objTip != null)
        {
            objTip.FilePath = string.Empty;
            if (objBus.Update(objTip))
            {
                DeleteImage(this.ThumImage);
                Response.Redirect("BannerDetail.aspx" + this.GetPageQuery);
            }
        }
    }
    private void BindImage(HtmlTableRow trImage, System.Web.UI.WebControls.Image img, LinkButton lbtnDelete, string value)
    {
        string imagePage = "~/" + clsConfigData.DEFAULT_UPLOAD_BANNER_FOLDER + value;
        if (File.Exists(this.Page.Server.MapPath(imagePage)))
        {
            img.ImageUrl = imagePage;
            lbtnDelete.Visible = true;
            trImage.Visible = true;
        }
        else trImage.Visible = false;
    }
    #endregion

    #region Validate Data
    protected void CheckSImageValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsImage.IsValidImage();
    }
    protected void CheckDateValid(object source, ServerValidateEventArgs args)
    {
        
        args.IsValid = false;
        DateTime dtResult = clsConvert.Date(args.Value);
        if (dtResult != DateTime.MinValue)
            args.IsValid = true;
    }
    private bool ValidateForm()
    {
        if (F_StartDate.Text==string.Empty)
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_REQUIREMENT, "Starting Date"); ;
            return false;
        }
        if (F_EndDate.Text == string.Empty)
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_REQUIREMENT, "Ending Date"); ;
            return false;
        }
        //string.Format(Resources.Resource.MSG_REQUIREMENT, "Ending Date")
        if (!clsImage.IsValidImage())
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Image"); ;
            return false;
        }
        DateTime dtStart = clsConvert.Date(F_StartDate.Text.Trim());
        if (dtStart == DateTime.MinValue)
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Starting Date"); ;
            return false;
        }
        DateTime dtEnd = clsConvert.Date(F_EndDate.Text.Trim());
        if (dtEnd == DateTime.MinValue)
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_VALID, "Ending Date"); ;
            return false;
        }
        System.TimeSpan diffResult = dtEnd.Subtract(dtStart);
        if (diffResult.Days >= 0)
            return true;
        else 
        {
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_COMPARE_MORE_THAN, "Ending Date", "Starting Date"); ;
            return false;
        }
    }
    #endregion
}